﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Devdream.IDAL;
using System.Linq.Expressions;
using System.Data.Entity;
namespace Devdream.DAL
{
    /// <summary>
    /// 创库基类
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class BaseRepository<T>:InterfaceBaseRepository<T> where T:class
    {
        protected DevdreamDbContent nContext = ContextFactory.GetCurrentContext();
        public T Add(T entity)
        {
            nContext.Entry<T>(entity).State = EntityState.Added;
            nContext.SaveChanges();
            return entity;
        }

        public int Count(System.Linq.Expressions.Expression<Func<T, bool>> predicate)
        {
            return nContext.Set<T>().Count(predicate);
        }

        public bool Update(T entity)
        {
            nContext.Set<T>().Attach(entity);
            nContext.Entry<T>(entity).State = EntityState.Modified;
            return nContext.SaveChanges() > 0;
        }

        public bool Delete(T entity)
        {
            nContext.Set<T>().Attach(entity);
            nContext.Entry<T>(entity).State = EntityState.Deleted;
            return nContext.SaveChanges() > 0;
        }

        public bool Exist(System.Linq.Expressions.Expression<Func<T, bool>> anyLambda)
        {
            return nContext.Set<T>().Any(anyLambda);
        }

        public T Find(System.Linq.Expressions.Expression<Func<T, bool>> whereLambda)
        {
            T _entity = nContext.Set<T>().FirstOrDefault<T>(whereLambda);
            return _entity;
        }

        public IQueryable<T> FindList<S>(System.Linq.Expressions.Expression<Func<T, bool>> whereLambda, bool isASC, System.Linq.Expressions.Expression<Func<T, S>> orderLambda)
        {
            var _list = nContext.Set<T>().Where<T>(whereLambda);
            if (isASC)
                _list = _list.OrderBy<T, S>(orderLambda);
            else
                _list = _list.OrderByDescending<T, S>(orderLambda);
            return _list;
        }

        public IQueryable<T> FindPageList<S>(int pageIndex, int pageSize, out int totalRecord, System.Linq.Expressions.Expression<Func<T, bool>> whereLambda, bool isASC, System.Linq.Expressions.Expression<Func<T, S>> orderLambda)
        {
            var _list = nContext.Set<T>().Where<T>(whereLambda);
            totalRecord = _list.Count();
            if (isASC)
                _list = _list.OrderBy<T, S>(orderLambda).Skip<T>((pageIndex - 1) * pageSize).Take<T>(pageSize);
            else
                _list = _list.OrderByDescending<T,S>(orderLambda).Skip<T>((pageIndex - 1) * pageSize).Take<T>(pageSize);
            return _list;

        }
    }
}
